<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use buwang\base\MemberBaseController;
use think\App;
use app\Request;
use app\manage\model\AuthNode;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member;
use app\manage\model\Token;
use buwang\service\UserService;

class Login extends MemberBaseController
{
    // 获取后台菜单初始化数据
    public function getSystemInit(Request $request)
    {
        $admin = $request->userInfo();
        //得到登录管理员id
        $member_id = $admin['id'];  //id=1为超级管理员，拥有全部权限
        $homeInfo = [
            'title' => '首页',
            'href' => '/manage/member.index/dashboard',
        ];
        $logoInfo = [
            'title' => $admin['nickname'],
            'image' => '/layui/images/logo.png',
            'href' => '/'
        ];
        $menuInfo = Member::getMenuList($member_id);
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }

    public function user()
    {
        //\think\facade\Swoole::reload();

//        $server = app('swoole.server');
//        $server->reload();


//        $manager = app(Manager::class); // 或 app('swoole.manager')
//        $server = $manager->getServer(); // 获取 Swoole\Server 实例
//        $server->reload()
//        return $this->success('successful');

        $member_id = $this->uid;
        $Member = Member::getTop($member_id);
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);
            //TODO 获取搜索条件
            //TODO 如果有不属于表内的字段,查询会报错
            $where = request()->get();
            unset($where['page']);
            unset($where['limit']);
            foreach ($where as $k => $v) {
                if (!$v && $v !== '0' && $v !== 0 && $v !== false) {
                    unset($where[$k]);
                }
            }

            try {
                //得到所有登录用户
                $groups = Member::valiWhere()
                    ->where($where)
                    ->where(function ($query) use ($member_id) {
                        $query->where('parent_id', $member_id)->whereOr('id', $member_id);
                    })
                    ->page($page, $limit)
                    ->order('id desc')->select()->toArray();

                $memberConfigIds = array();
                //组合树
                foreach ($groups as $val) {
                    $memberConfigIds[] = $val['id'];
                }
                $total = Member::valiWhere()
                    ->where($where)
                    ->where(function ($query) use ($member_id) {
                        $query->where('parent_id', $member_id)->whereOr('id', $member_id);;
                    })
                    ->count();
                //返回数据
                $list = array();
                foreach ($groups as $group) {
                    $data = $group;
                    $data['my'] = false;
                    $data['is_top'] = false;
                    if ($group['id'] == $member_id) $data['my'] = true;
                    if ($group['id'] == $Member['id']) $data['is_top'] = true;
                    $data['rules'] = [];
                    $data['auth_group_access'] = [];
                    //查询所有角色，以逗号拼接
                    $rules = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('group_id');
                    $names = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('name');
                    if ($rules) {
                        $data['rules'] = $rules;
                    }
                    if ($names) {
                        $data['auth_group_access'] = $names;
                    }
                    //列表中不存在该父id则父id为0
                    if (!in_array($group['parent_id'], $memberConfigIds)) $data['parent_id'] = 0;
                    $list[] = $data;
                }
                $list = array_merge(AuthNode::tree($list, 'id', 'id', 'parent_id'));
            } catch (\think\db\exception\PDOException $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getData()]);
            }

            $data = compact("total", 'list');
            return $this->success('successful', $data);
        }

        return view('');
    }


    /**
     * 编辑管理组
     * @return \think\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        if ($this->request->isPost()) {
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            $param = $this->request->param();
            $result = Member::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(Member::getError());
            }
        }
        $id = $this->request->get('id');
        $data = AuthGroupAccess::getMemberFind($id);
        $list = Member::select()->toArray();
        return view('form', ['data' => $data, 'list' => $list]);
    }

    /**
     * 添加管理组
     * @param Request $request
     * @return \think\Response|\think\response\View
     */
    public function add(Request $request)
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        $user = $request->userInfo();
        $member_id = $user['id'];
        if ($this->request->isPost()) {
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            $param = $this->request->param();

            $param['username'] = $param['nickname'] = 'bw' . $param['mobile'];
            $param['safe_password'] = '123456';

            $result = Member::createAdmin($param, $member_id, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(Member::getError());
            }
        }
        return view('form');
    }


    /**
     * 删除
     * @menu true
     * @param int $ids 主键,删除多行时,拼接
     */
    public function delete($ids = 0)
    {
        return $this->error('子租户无权操作');
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);

        if (request()->isPost()) {
            if (!$ids) return $this->error('参数有误');
            $list = Member::where('id', 'in', $ids)->where('parent_id', '=', $Member['id'])->select();
            if (!$list) return $this->error('记录不存在');
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            Member::startTrans();
            try {
                foreach ($list as $item) {
                    Member::destroy($item['id']);
                    //删除角色中间表
                    $ids = AuthGroupAccess::where('uid', $item['id'])->where('scopes', 'member')->column('id');
                    if ($ids) {
                        AuthGroupAccess::destroy($ids);
                    }
                }
                Member::commit();
            } catch (\Exception $e) {
                Member::rollback();
                return $this->error('删除失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }
    }


    /**
     * 退出登录
     */
    public function loginOut()
    {
        $admin = $this->request->user;
        $scopes = $this->request->scopes;
        if ($this->request->isPost()) {
            $token = $this->request->server('HTTP_TOKEN', cookie('token'));  //TODO：改变顺序 头 -- cookie -- session -- 参数
            //如果不存在，往session中取
            if (!$token) $token = UserService::getLogin('token');
            //如果不存在，往参数中取
            if (!$token) $token = $this->request->param('token');
            if (!$token) return $this->error('已退出登录，勿重复点击');
            $res = Token::deleteToken($token, $admin['id'], $scopes, true);
            if (!$res) {
                return $this->error(Token::getError('操作失败'));
            } else {
                return $this->success('退出成功');
            }
        }
    }

    /**
     * 更改开启状态
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setStatus()
    {
        $member_id = $this->uid;
        $Member = Member::getTop($member_id);
        if ($member_id != $Member['id']) return $this->error('子租户无权操作');
        if (request()->isAjax()) {
            $id = input('id/d');
            $data = Member::where('parent_id', $Member['id'])->find($id);
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
            $data->save();
            return $this->success('successful');
        }
    }

    /**
     * 租户基本资料
     */
    public function userSetting()
    {
        if($this->sub_id){
            $this->user->id = $this->sub_id;
            $this->uid = $this->sub_id;
        }
        if ($this->request->isPost()) {
            $param = $this->request->only(['unbind','avatar','nickname']);
            //解绑微信
            if (isset($param['unbind'])) {
                $this->user->openid = null;
                $this->user->save();
                return $this->success('解绑成功');
            }

            $param['id'] = (string)$this->uid;

            try {
                if(!$param['avatar']) return $this->error('用户头像不能为空');
                if(!$param['nickname'] || !preg_match('/^[A-Za-z][A-Za-z0-9_\x{4e00}-\x{9fa5}]{3,15}$/u',$param['nickname'])) return $this->error('昵称不能为空，或者长度应该在8到15位');
                $result = Member::updateAdmin($param, true);
                if ($result) {
                    return $this->success('操作成功');
                } else {
                    return $this->error(Member::getError());
                }
            } catch (\Exception $e) {
                return $this->error($e->getFile() . '-' . $e->getLine() . '-' . $e->getMessage());
            }
        }
        $data = \app\common\model\Member::with('wallet')->hidden(['password', 'safe_password'])->find($this->uid);
        if(!$data){
            return $this->error('API用户信息获取失败,$user='.json_encode($this->user));
        }
        //$url = sysuri('/api/official/bindQrcodeOpenid',['token'=>$this->token],false,true);
        $domain = request()->domain();
        $url = $domain . '/api/official/bindQrcodeOpenid?token=' . urlencode($this->token);
        //兼容处理前后端分离
        if ($this->request->isAjax()) {
            //return $this->success('success', ['data' => $data,'dashboard'=>0,'url'=>$data['openid'] ? '': $url]);

            $url = isset($data['openid']) && !empty($data['openid']) ? '' : $url;
            return $this->success('success', ['data' => $data,'dashboard'=>0,'url'=>$url]);
        }else{
            $this->layout && $this->app->view->engine()->layout($this->layout);

            $this->assign('jsConfig', ['url'=>$data['openid'] ? '': $url]);
            return $this->fetch('user_setting', ['data' => $data]);
        }

    }

    public function userPassword()
    {
        if($this->sub_id){
            $this->user->id = $this->sub_id;
            $this->uid = $this->sub_id;
        }
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = Member::updatePassword($param, true);
            if ($result) {
                //如果变更了操作密码
                if (isset($result['password']) && $result['password']) {

                }
                return $this->success('操作成功', $result);
            } else {
                return $this->error(Member::getError());
            }
        }
        $data = AuthGroupAccess::getMemberFind($this->uid);
        return view('user_password', ['data' => $data]);
    }
}
